/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package vista;

import Consultas.Logica;
import Consultas.logicaCompra;
import com.sun.media.sound.ModelOscillator;
import java.sql.SQLException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author USUARIO WINDOWS
 */
public class vistaCompras extends javax.swing.JFrame {

    /**
     * Creates new form vistaCompras
     */
    public vistaCompras() throws SQLException {
        initComponents();
        logica = new Logica();
        proveedores = logica.obtenerProveedores();
        if (proveedores.length != 0) {
            actualizarProveedores(proveedores);
        }
        productos = logica.obtenerProductos();
        if (productos.length != 0) {
            actualizarProductos(productos);
        }
        
        modelo = (DefaultTableModel) tableCompra.getModel();
        model = (DefaultTableModel) TCompra.getModel();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        entityManager1 = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("Moto_LocuraPU").createEntityManager();
        jLabel1 = new javax.swing.JLabel();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        boxProveedores = new javax.swing.JComboBox();
        boxProductos = new javax.swing.JComboBox();
        jLabelProducto = new javax.swing.JLabel();
        jLabelProveedores = new javax.swing.JLabel();
        jLabelcantidadProductos = new javax.swing.JLabel();
        tfCantidad = new javax.swing.JTextField();
        bAgregar = new javax.swing.JButton();
        bConfirmar = new javax.swing.JButton();
        jLabelTitulo = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tableCompra = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        TCompra = new javax.swing.JTable();
        jBAgregarCompra = new javax.swing.JButton();
        jLIdCompra = new javax.swing.JLabel();
        jTNumeroCompra = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jBCargarPedido = new javax.swing.JButton();
        jScrollPane4 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton2 = new javax.swing.JButton();

        jLabel1.setText("jLabel1");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Compras a los Proveedores");

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setForeground(new java.awt.Color(204, 204, 255));

        boxProveedores.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        boxProveedores.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boxProveedoresActionPerformed(evt);
            }
        });

        boxProductos.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabelProducto.setText("Productos");

        jLabelProveedores.setText("Proveedores");

        jLabelcantidadProductos.setText("Cantidad de productos");

        tfCantidad.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfCantidadActionPerformed(evt);
            }
        });

        bAgregar.setBackground(new java.awt.Color(204, 204, 255));
        bAgregar.setText("Agregar Producto");
        bAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bAgregarActionPerformed(evt);
            }
        });

        bConfirmar.setText("Confirmar ");
        bConfirmar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bConfirmarActionPerformed(evt);
            }
        });

        jLabelTitulo.setBackground(new java.awt.Color(153, 153, 255));
        jLabelTitulo.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabelTitulo.setForeground(new java.awt.Color(153, 153, 255));
        jLabelTitulo.setText("Datos para la compra");

        tableCompra.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
            },
            new String [] {
                "Producto", "Proveedor", "Cantidad","Precio Unitario","Precio Total"
            }
        ));
        jScrollPane2.setViewportView(tableCompra);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(111, 111, 111)
                        .addComponent(bAgregar))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(126, 126, 126)
                        .addComponent(jLabelTitulo))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(40, 40, 40)
                        .addComponent(jLabelcantidadProductos))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(41, 41, 41)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabelProveedores)
                                .addGap(154, 154, 154)
                                .addComponent(boxProveedores, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabelProducto)
                                .addGap(167, 167, 167)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(tfCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(boxProductos, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE))))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 42, Short.MAX_VALUE)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(33, 33, 33))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(bConfirmar, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(143, 143, 143))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabelTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(40, 40, 40)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabelProveedores)
                            .addComponent(boxProveedores, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(32, 32, 32)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabelProducto)
                            .addComponent(boxProductos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabelcantidadProductos)
                            .addComponent(tfCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(48, 48, 48)
                        .addComponent(bAgregar))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(25, 25, 25)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
                .addComponent(bConfirmar)
                .addGap(24, 24, 24))
        );

        jTabbedPane1.addTab("Realizar pedido", jPanel1);

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        TCompra.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "IdCompra", "estado", "fecha", "total", "idPersona", "idProveedor"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Integer.class, java.lang.Object.class, java.lang.Float.class, java.lang.Integer.class, java.lang.Integer.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPane1.setViewportView(TCompra);

        jPanel2.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 40, 450, 140));

        jBAgregarCompra.setText("Agregar Compra");
        jBAgregarCompra.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBAgregarCompraActionPerformed(evt);
            }
        });
        jPanel2.add(jBAgregarCompra, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 270, -1, -1));

        jLIdCompra.setText("Ingrese el número de la compra:");
        jLIdCompra.setToolTipText("");
        jPanel2.add(jLIdCompra, new org.netbeans.lib.awtextra.AbsoluteConstraints(280, 210, 200, -1));
        jPanel2.add(jTNumeroCompra, new org.netbeans.lib.awtextra.AbsoluteConstraints(500, 210, 90, -1));

        jButton1.setText("Cargar pedidos en espera");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 100, 180, 30));

        jTabbedPane1.addTab("Registrar Pedido", jPanel2);

        jPanel3.setBackground(new java.awt.Color(255, 255, 255));
        jPanel3.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jBCargarPedido.setText("Cargar Pedido");
        jBCargarPedido.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBCargarPedidoActionPerformed(evt);
            }
        });
        jPanel3.add(jBCargarPedido, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 130, 160, 30));

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null}
            },
            new String [] {
                "idCompra", "estado", "fecha", "total", "idPersona", "idProveedor"
            }
        ));
        jScrollPane4.setViewportView(jTable1);

        jPanel3.add(jScrollPane4, new org.netbeans.lib.awtextra.AbsoluteConstraints(280, 60, 510, 160));

        jButton2.setText("Descartar Pedido");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel3.add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(490, 250, -1, -1));

        jTabbedPane1.addTab("Descartar Pedido", jPanel3);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.Alignment.TRAILING)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tfCantidadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfCantidadActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_tfCantidadActionPerformed

    private void bAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bAgregarActionPerformed
        // TODO add your handling code here:
        modelo.addRow(new Object[]{boxProductos.getSelectedItem(),
            boxProveedores.getSelectedItem(),
            tfCantidad.getText(),
            logica.precioProductos[boxProductos.getSelectedIndex()],
            (logica.precioProductos[boxProductos.getSelectedIndex()] * Integer.parseInt(tfCantidad.getText())) + ""});
        actualizarBoxProveedores("" + boxProveedores.getSelectedItem());
    }//GEN-LAST:event_bAgregarActionPerformed

    private void bConfirmarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bConfirmarActionPerformed
        try {
            // TODO add your handling code here:
            logica.ingresarCompra(obtenerTotalCompra(), getIdAdmin(), obtenerIdProveedor("" + tableCompra.getValueAt(0, 1)));
            insertarDetalleCompra();

        } catch (SQLException ex) {
            Logger.getLogger(vistaCompras.class.getName()).log(Level.SEVERE, null, ex);
        }


    }//GEN-LAST:event_bConfirmarActionPerformed

    private void jBAgregarCompraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBAgregarCompraActionPerformed
        // TODO add your handling code here:
        
        
    }//GEN-LAST:event_jBAgregarCompraActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        
           /* logica.obtenerPedidosEspera()
        
                model.addRow( new Object []{logica.idCompra[1],logica.estado[2],logica.fecha[3],logica.total[4],logica.idEmpleado[5],logica.idProveedor[6]});
                }*/
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jBCargarPedidoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBCargarPedidoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jBCargarPedidoActionPerformed

    private void boxProveedoresActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boxProveedoresActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_boxProveedoresActionPerformed

        
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(vistaCompras.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(vistaCompras.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(vistaCompras.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(vistaCompras.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    new vistaCompras().setVisible(true);
                } catch (SQLException ex) {
                    Logger.getLogger(vistaCompras.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable TCompra;
    private javax.swing.JButton bAgregar;
    private javax.swing.JButton bConfirmar;
    private javax.swing.JComboBox boxProductos;
    private javax.swing.JComboBox boxProveedores;
    private javax.persistence.EntityManager entityManager1;
    private javax.swing.JButton jBAgregarCompra;
    private javax.swing.JButton jBCargarPedido;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLIdCompra;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabelProducto;
    private javax.swing.JLabel jLabelProveedores;
    private javax.swing.JLabel jLabelTitulo;
    private javax.swing.JLabel jLabelcantidadProductos;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTextField jTNumeroCompra;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable tableCompra;
    private javax.swing.JTextField tfCantidad;
    // End of variables declaration//GEN-END:variables
   private String[] proveedores;
    private String[] productos;
    private Logica logica;
    private DefaultTableModel modelo;
    private DefaultTableModel model;
    private String[] pedidos;
    
    String[] listaProveedores;
    private int idAdmin;

    public int getIdAdmin() {
        return idAdmin;
    }

    public void setIdAdmin(int idAdmin) {
        this.idAdmin = idAdmin;
    }

    public void actualizarProveedores(String[] vector) {
        if (vector.length != 0) {
            ComboBoxModel comb = new DefaultComboBoxModel(vector);
            boxProveedores.setModel(comb);

        }
    }

    public void actualizarBoxProveedores(String proveedor) {

        String[] listaProveedores = new String[1];
        listaProveedores[0] = proveedor;
        ComboBoxModel comb = new DefaultComboBoxModel(listaProveedores);
        boxProveedores.setModel(comb);

    }

    public void actualizarProductos(String[] vector) {
        if (vector.length != 0) {
            ComboBoxModel comb = new DefaultComboBoxModel(vector);
            boxProductos.setModel(comb);

        }

    }

    public double obtenerTotalCompra() {

        double total = 0.0;
        for (int i = 0; i < tableCompra.getRowCount(); i++) {
            total += Double.parseDouble((String) tableCompra.getValueAt(i, 4));
        }
        return total;
    }

    public int obtenerIdProveedor(String nombreProveedor) throws SQLException {

        int idProveedor = 0;
        for (int i = 0; i < logica.obtenerProveedores().length; i++) {
            if (logica.obtenerProveedores()[i].equals(nombreProveedor)) {
                idProveedor = i + 1;
            }
        }
        return idProveedor;
    }

    public int obtenerIdProducto(String nombreProducto) throws SQLException {

        int idProducto = 0;
        for (int i = 0; i < logica.obtenerProductos().length; i++) {
            if (logica.obtenerProductos()[i].equals(nombreProducto)) {
                idProducto = i + 1;
            }
        }
        return idProducto;
    }

    public void insertarDetalleCompra() throws SQLException {
        Double total = 0.0;
        Double precioUnitario = 0.0;
        for (int j = 0; j < tableCompra.getRowCount(); j++) {
            total = Double.parseDouble((String) tableCompra.getValueAt(j, 4));                      
            int cantidad = Integer.parseInt((String) tableCompra.getValueAt(j, 2));            
            precioUnitario = Double.parseDouble(""+tableCompra.getValueAt(j, 3));
                
            logica.ingresarDetalleCompra(total, cantidad, obtenerIdProveedor("" + tableCompra.getValueAt(0, 1)),
                    precioUnitario, obtenerIdProducto("" + tableCompra.getValueAt(0, 0)));

        }
        
        

    }
       
        
        
    
    
}
